<?php

/* force ajax mode*/
$force_ajax_mode = true;

/* requires */
require_once('./config.inc.php');

if (_getRequestParameter('do'))
{
	$do = _getRequestParameter('do');
	
	if ($do == 'updateId3Tag')
	{
		$filename = _getFileNameFromMd5(_getRequestParameter('step'), _getRequestParameter('file'));
		if (file_exists($filename))
		{
			try {
				$id3 = new ID3v2($filename);
				$id3->{_getRequestParameter('tag')}->text = utf8_encode(_getRequestParameter('value'));
				$id3->write();
				echo 'done';
			}
			catch (ID3_Exception $e) {
					echo 'error:'.$e->getMessage();
					die;
			}
		}
		else echo 'error: file is not found...';
	}
	elseif ($do == 'moveFileToTheNextStep')
	{
		$filename = _getFileNameFromMd5(_getRequestParameter('step'), _getRequestParameter('file'));
		$currentStepName = _getRequestParameter('currentStepName');
		die(move_a_file_to_the_next_step($currentStepName, $filename) ? 'done' : '');
	}
	elseif ($do == 'updateListing')
	{
		$listing = new Listing(
			_getRequestParameter('request_name'),
			getListingData(_getRequestParameter('subdir')),
			false,
			_getRequestParameter('page'),
			_getRequestParameter('item_per_page'),
			_getRequestParameter('listing_type'),
			_getRequestParameter('sort_by'),
			_getRequestParameter('sort_by_direction'),
			_getRequestParameter('filter'),
			_getRequestParameter('filter_value'),
			_getRequestParameter('numberOfPagesNumbersToShow')
		);
		
		$fullReload = _getRequestParameter('full_reload');
		if($fullReload && $fullReload == 'true')
			die($listing->fetch());
		else
			die($listing->fetchAjax());
	}
	elseif ($do == 'refreshSteps')
	{
		$smarty->assign('steps',$steps);
		$smarty->assign('currentStepName',$currentStep['name']);
		$smarty->display('ajax_steps.tpl');
	}
	elseif ($do == 'multiple_action')
	{
		if (_getRequestParameter('action') == 'delete')
		{
			$md5s = _getRequestParameter('multiple_action');
			if (count($md5s) > 0)
			{
				foreach ($md5s as $md5 => $value)
				{
					$filename = _getFileNameFromMd5(_getRequestParameter('step'), $md5);
					if (file_exists($filename))
						unlink($filename);
					else
						die('file '.$filename.' doesn\'t exist. So it could not be deleted...');
				}
				die('done');
			}
			else die('no file selected...');
		}
		elseif (_getRequestParameter('action') == 'valid')
		{
			$md5s = _getRequestParameter('multiple_action');
			if (count($md5s) > 0)
			{
				foreach ($md5s as $md5 => $value)
				{
					$filename = _getFileNameFromMd5(_getRequestParameter('step'), $md5);
					$currentStepName = _getRequestParameter('step');
					if (!move_a_file_to_the_next_step($currentStepName, $filename))
						die;
				}
				die('done');
			}
			else die('no file selected...');
		}
		else echo 'error: action to execute on multiple item not recognize...';
	}
	else echo 'error: action not recognize...';
}
else echo 'error: nothing to do...';
